package cn.zhangxin.newyear.system.verifycode.controller;

import cn.zhangxin.newyear.system.verifycode.domain.EmailCode;
import cn.zhangxin.newyear.system.verifycode.service.IVerifycodeService;
import cn.zhangxin.newyear.utils.AjaxResult;
import cn.zhangxin.newyear.utils.BusinessException;
import cn.zhangxin.newyear.utils.StrUtils;
import cn.zhangxin.newyear.utils.VerifyCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/*
 获得验证码
 */
@RestController
@RequestMapping("/vcode")
@Api(value = "验证码API",description="验证码验证")
public class VerifyContController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IVerifycodeService verifycodeService;

    //获得图片验证码
    @GetMapping("/getVCode/{imageCodeKey}")
    @ApiOperation(value = "获取图片验证码")
    public AjaxResult getVerificationCode(@PathVariable("imageCodeKey") String imageCodeKey) {

        try {
            //获得四位数的验证码
            String code = StrUtils.getRandomString(4);
            //设置验证码的时间
            redisTemplate.opsForValue().set(imageCodeKey,code,5, TimeUnit.MINUTES);
            //生成图片验证码的base64
            String getImgCode = VerifyCodeUtils.VerifyCode(110, 40, code);//生成验证码图片base64
            return AjaxResult.success().setData(getImgCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error().setData("网络异常");
    }
    //发送邮箱
    @PostMapping("/sentEmailCode")
    @ApiOperation(value = "发送邮箱验证码")
    public AjaxResult sentEmailCode(@RequestBody EmailCode emailCode){
        try {
            verifycodeService.sentEmailCode(emailCode);
            return AjaxResult.success().setMsg("邮箱验证码已经发送");
        } catch (BusinessException b){
            return AjaxResult.error().setMsg(b.getMessage());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
